package com.telecom.service.impl;

import com.telecom.common.convention.errorcode.BaseErrorCode;
import com.telecom.common.convention.exception.ServiceException;
import com.telecom.mapper.MealMapper;
import com.telecom.mapper.OrderMapper;
import com.telecom.mapper.UserMapper;
import com.telecom.pojo.dto.admin.work.QueryDailyOrderStatisticsDTO;
import com.telecom.pojo.vo.admin.meal.MealRankingVO;
import com.telecom.pojo.vo.admin.workspace.BusinessDataVO;
import com.telecom.pojo.vo.admin.workspace.OrderOverViewVO;
import com.telecom.service.WorkspaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 工作台业务实现类
 */
@Service
@Slf4j
public class WorkspaceServiceImpl implements WorkspaceService {
    
    @Resource
    private UserMapper userMapper;
    
    @Resource
    private OrderMapper orderMapper;
    
    @Resource
    private MealMapper mealMapper;

    @Override
    public BusinessDataVO getBusinessData() {
        log.info("开始查询今日运营数据");
        
        BusinessDataVO businessData = new BusinessDataVO();
        
        try {
            // 查询今日套餐订单数
            Integer todayMealOrderCount = orderMapper.countTodayMealOrders();
            businessData.setTodayMealOrderCount(todayMealOrderCount != null ? todayMealOrderCount : 0);
            
            // 查询注册用户总数
            Integer users = userMapper.countTotalUsers();
            businessData.setUsersNumber(users != null ? users : 0);
            
            // 查询今日营业额
            BigDecimal todayTurnover = orderMapper.getTodayTurnover();
            businessData.setTodayTurnover(todayTurnover != null ? todayTurnover : BigDecimal.ZERO);
            
            // 计算订单满意率
            Map<String, Object> satisfactionData = orderMapper.getOrderSatisfactionRate();
            Object totalObj = satisfactionData.get("total");
            Object satisfiedObj = satisfactionData.get("satisfied");
            
            long total = totalObj != null ? ((Number) totalObj).longValue() : 0;
            long satisfied = satisfiedObj != null ? ((Number) satisfiedObj).longValue() : 0;
            double orderSatisfaction = total > 0 ? Math.round((double) satisfied / total * 10000) / 100.0 : 0.0;
            businessData.setOrderSatisfactionForWeek(orderSatisfaction);
            
            log.info("今日运营数据查询完成: 套餐订单数={}, 用户总数={}, 营业额={}, 7天内满意率={}%",
                    todayMealOrderCount, users, todayTurnover, orderSatisfaction);
            
        } catch (Exception e) {
            log.error("查询今日运营数据失败", e);
            // 返回默认值
            throw new ServiceException("计算运营数据出错", BaseErrorCode.SERVICE_ERROR);
        }
        
        return businessData;
    }

    @Override
    public List<OrderOverViewVO> getOrderOverview(QueryDailyOrderStatisticsDTO queryDailyOrderStatisticsDTO) {
        log.info("开始查询订单统计数据，日期: {}", queryDailyOrderStatisticsDTO.getDate());
        
        try {
            List<OrderOverViewVO> orderOverview = orderMapper.getOrderOverviewByMealType(queryDailyOrderStatisticsDTO.getDate());
            log.info("订单统计数据查询完成，共{}个餐型的数据", orderOverview.size());
            return orderOverview;
        } catch (Exception e) {
            log.error("查询订单统计数据失败，日期: {}", queryDailyOrderStatisticsDTO.getDate(), e);
            return List.of();
        }
    }

    @Override
    public List<MealRankingVO> getHotMealRanking() {
        log.info("开始查询热门套餐排行");
        
        try {
            List<MealRankingVO> hotMealRanking = mealMapper.getHotMealRanking();
            
            // 在Service层添加排名逻辑（SQL已经LIMIT 10，这里只需要设置排名）
            for (int i = 0; i < hotMealRanking.size(); i++) {
                hotMealRanking.get(i).setRank(i + 1);
            }
            
            log.info("热门套餐排行查询完成，共{}条记录", hotMealRanking.size());
            return hotMealRanking;
        } catch (Exception e) {
            log.error("查询热门套餐排行失败", e);
            return List.of();
        }
    }
}